﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUI;
using SysManage.BLL;
using ZHDJ.Core;
using ZHDJ.Core.Caching;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.BLL;
using ZHDJ.Data.DataCaching;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.Org;
using ZHDJ.Web.WS.Proxys;
using ZHDJ.WebPage;

namespace SysManage.Module.Org
{
    public partial class PartyOrgBranchEidt : PageBase
    {
        #region ViewPower
        public string id { get { return GetQueryIntValue("id"); } }
        public string IsBranchCenter { get { return GetQueryIntValue("IsBranchCenter"); } }
        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "PartyOrgBranchAdd";
            }
        }

        /// <summary>
        /// 组织间的关系
        /// </summary>
        /// <returns></returns>
        public delegate void PartyOrgBranchRelationHandler();
        public PartyOrgBranchRelationHandler handler;
        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        public void BindData()
        {
            btnSave.Hidden = true;
            btnSaveClose.Hidden = true;
            btnClose.Hidden = true;
            ControlBusiness.ControlBindDataDictionary(ddlBranchMark, SysDataDictionary.BranchMarkKey, true);
            ControlBusiness.ControlBindDataDictionary(ddlBranchType, SysDataDictionary.BranchTypeKey, true);
            ControlBusiness.ControlBindDataDictionary(ddlSocialParty, SysDataDictionary.BranchTwoNew, true);
            if (!IsSystemAdmin)
            {
                this.ppParentBranch.Enabled = false;
            }
            if (IsBranchCenter == "1")
            {
                btnSave.Hidden = false;
                Panel1.ShowBorder = true;
            }
            else
            {
                btnSaveClose.Hidden = false;
                btnClose.Hidden = false;
            }
        }

        private void LoadData()
        {

            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            string id = GetQueryIntValue("id");
            if (id != "")
            {

                var current = DB.PartyOrgBranchs.Find(id);
                txtBranchName.Text = current.BranchName;
                ppParentBranch.Value = current.ParentBranchID;
                if (!string.IsNullOrEmpty(current.ParentBranchID))
                {
                    ppParentBranch.Text = ControlBusiness.GetBranchPickerText(current.ParentBranchID);
                    frParentBranch.Hidden = false;
                }
                else
                {
                    frParentBranch.Hidden = true;
                }
                ddlBranchMark.SelectedValue = current.BranchMark;
                ddlBranchType.SelectedValue = current.BranchType;
                if (current.BranchType == "3")
                {
                    frTwoNew.Hidden = false;
                    ddlSocialParty.SelectedValue = current.SocialParty.ToString();
                }
                else
                {
                    frTwoNew.Hidden = true;
                }
                txtLinkMan.Text = current.LinkMan;
                txtLinkPhone.Text = current.LinkPhone;
                txtAddress.Text = current.Address;
                txtDescription.Text = current.Description;
                ppBranchAdmin.Value = string.Join(",", DB.PartyOrgBranchAdmins.Where(a => a.BranchID == current.BranchID).Select(a => a.LoginID).ToArray());
                ppBranchAdmin.Text = ControlBusiness.GetMembersPickerText(ppBranchAdmin.Value);
                var PartyWorker = string.Join(",", DB.PartyOrgMembers.Where(a => a.BranchID == current.BranchID && a.IsPartyWorker == true).Select(a => a.LoginID).ToArray());
                txtPartyWorker.Text = ControlBusiness.GetMembersPickerText(PartyWorker);
                hdFileId.Text = current.ImageUrl;
                if (!string.IsNullOrEmpty(hdFileId.Text))
                {
                    imgPhoto.ImageUrl = UpFileBusiness.GetFileUrl(hdFileId.Text);
                    imgPhoto.ImageWidth = Unit.Pixel(300);

                    PageContext.RegisterStartupScript("ReDoLayout();");
                }
                txtXPoint.Text = current.XPoint;
                txtYPoint.Text = current.YPoint;
            }

        }
        private void SaveData()
        {
            string id = GetQueryIntValue("id");
            var q = DB.PartyOrgBranchs;

            if ((q.Where(a => a.BranchName == txtBranchName.Text && a.BranchID != id)).Any())
            {
                Alert.Show("组织名已存在，请重新输入！", String.Empty);
                return;
            }

            var isChangeBranchID = false;

            PartyOrgBranch current;
            if (id != "")
            {
                //更新
                current = q.Find(id);
                if (current == null)
                {
                    Alert.Show("参数错误！", String.Empty);
                    return;
                }
                current.ModifyTime = DateTime.Now;
                isChangeBranchID = current.ParentBranchID != this.ppParentBranch.Value;
            }
            else
            {
                current = new PartyOrgBranch { BranchID = StringHelper.NewID };
                current.CreateTime = DateTime.Now;
                current.ModifyTime = DateTime.Now;
                isChangeBranchID = true;
                DB.PartyOrgBranchs.Add(current);
            }

            current.BranchName = txtBranchName.Text;
            current.ParentBranchID = ppParentBranch.Value;

            current.BranchMark = ddlBranchMark.SelectedValue;
            current.BranchType = ddlBranchType.SelectedValue;
            current.LinkMan = txtLinkMan.Text;
            current.LinkPhone = txtLinkPhone.Text;
            current.Address = txtAddress.Text;
            current.Description = txtDescription.Text;
            if (!string.IsNullOrEmpty(hdFileId.Text))
            {
                current.ImageUrl = hdFileId.Text;
            }
            if (!string.IsNullOrEmpty(ddlSocialParty.SelectedValue))
            {
                current.SocialParty = Convert.ToInt32(ddlSocialParty.SelectedValue);
            }
            current.XPoint = txtXPoint.Text;
            current.YPoint = txtYPoint.Text;

            if (DB.SaveChanges() > 0)
            {

                RoleHelper.DeleteRole(DB.PartyOrgBranchAdmins.Where(a => a.BranchID == current.BranchID).Select(a => a.LoginID).ToList(), SystemParameterCaching.Get(SystemParameterKey.BranchAdminRoleID));
                RoleHelper.AddRole(ppBranchAdmin.Value.Split(',').ToList(), SystemParameterCaching.Get(SystemParameterKey.BranchAdminRoleID));

            }
            //增加组织管理员
            if (ppBranchAdmin.Value.Trim() == "")
            {
                //return;
            }

            var admins = ppBranchAdmin.Value.Split(',').Where(a => a.Trim() != "").ToArray();
            PartyOrgBranchAdmin.UpdateAdmins(current.BranchID, admins);
            MemoryCacheManager Cache = new MemoryCacheManager();
            Cache.RemoveByPattern(@"^Cache_Branch");
            if (IsBranchCenter != "1")
            {
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            if (isChangeBranchID)
            {
                //用于服务判断是否重新生成组织之间的关系
                TempPara.UpdateInitBranchRelation("1");
            }
        }


        #endregion

        #region Events



        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData();
            //Alert.Show("添加成功！", String.Empty, ActiveWindow.GetHidePostBackReference());
        }


        protected void ddlBranchType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //选择两新组织
            if (ddlBranchType.SelectedValue == "3")
            {
                frTwoNew.Hidden = false;
            }
            else
            {
                frTwoNew.Hidden = true;
            }
        }
        #endregion

        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            var rs = UpFileBusiness.Upload(filePhoto, CurrentUser.LoginID, "组织图片", SysEnum.UploadFileType.uploadimage);
            if (rs.IsSuccess)
            {
                hdFileId.Text = rs.FileID;
                imgPhoto.ImageUrl = "~/" + rs.FileUrl;
                imgPhoto.ImageWidth = Unit.Pixel(300);

                PageContext.RegisterStartupScript("ReDoLayout();");
            }
            else
            {
                Alert.Show("上传失败！" + rs.Message, String.Empty);
            }
        }


    }
}

